python tutorial - Python object serialization : yaml and json - learn python - python programming
What is yaml?
- YAML (YAML Ain't Markup Language) is a human-readable data serialization language. It is commonly used for configuration files, but could be used in many applications where data is being stored (e.g. debugging output) or transmitted (e.g. document headers).
sample code
- strings do not require quotations. The specific number of spaces in the indentation is unimportant as long as parallel elements have the same left justification and the hierarchically nested elements are indented further. The sample above defines:
- An associative array with 7 top level keys
- The "items" key contains a 2-element array (or "list")
- Each element of which is itself an associative array with differing keys.
- Relational data and redundancy removal are displayed:
- The "ship-to" associative array content is copied from the "bill-to" associative array's content as indicated by the anchor (&) and reference (*) labels.
- Optional blank lines can be added for readability.
- Multiple documents can exist in a single file/stream and are separated by "---".
- An optional "..." can be used at the end of a file (useful for signaling an end in streamed communications without closing the pipe).
YAML vs JSON?
- Technically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON.
yaml validation
- We can use YAML Lint to validate *.yml file.
jason to yaml conversion
- Let's convert the following json to yaml:
Python code:
Output:
- If we open the data.yml :
- We can check our conversion is correct via yamllint:
Learn python - python tutorial - python-yamllint - python examples - python programs
- We can reads in the yaml and write it to json:
- The data.json looks like this:
- We can check the conversion using one of the online conversion tools:
Learn python - python tutorial - yml to json - python examples - python programs